//
//  ClearCache.m
//  开源中国
//
//  Created by hcios on 16/12/13.
//  Copyright © 2016年 鹿林. All rights reserved.
//

#import "ClearCache.h"

@implementation ClearCache


//找到要清除的文件
+ (float)clearCache{
    //创建路径
    NSString * path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    //初始化file
    NSFileManager * fileManager = [NSFileManager defaultManager];
    //定义计算后的文件大小
    float folderSize = 0.0;
    //判断文件是否存在
    if ([fileManager fileExistsAtPath:path]) {
        //拿到有文件的数组
        NSArray * childerFile = [fileManager subpathsAtPath:path];
        
        //拿到每个文件的名字
        for (NSString * fileName in childerFile) {
            //将路径接到一起
            NSString * fullPath = [path stringByAppendingPathComponent:fileName];
            folderSize += [self fileSizePath:fullPath];//计算文件大小
        }
    }
    return folderSize;
}
//计算文件的大小
+ (float)fileSizePath:(NSString *)path{
    NSFileManager * fileManager = [NSFileManager defaultManager];
    
    if ([fileManager fileExistsAtPath:path]) {
        long long size = [fileManager attributesOfItemAtPath:path error:nil].fileSize;
        if (size < 0) {
            return 0;
        }else return size/1024.0/1024.0;
    }
    return 0;
}

//清除缓存
+ (void)removedCache{
    NSString * path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    NSFileManager * manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:path]) {
        NSArray * childerFiles = [manager subpathsAtPath:path];
        for (NSString * fileName in childerFiles) {
            NSString * absolutePath = [path stringByAppendingPathComponent:fileName];
            [manager removeItemAtPath:absolutePath error:nil];
        }
    }
}


@end
